package com.hnx.admin.utils;

import io.micrometer.common.lang.NonNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/*
项目名称： core
创 建 人: 倔强的头发
创建日期： 2025/5/26   17:49:24 
描   述：
*/
@Component
public class SpringUtil implements BeanFactoryPostProcessor, ApplicationContextAware {

    private static ApplicationContext applicationContext;
    private static volatile boolean initialized = false;
    @Override
    public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
        applicationContext = context;
        initialized = true;
    }
    /**
     * 获取原始ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        if (!initialized) {
            throw new IllegalStateException("ApplicationContext not initialized yet");
        }
        return applicationContext;
    }
    public static <T> T getBean(Class<T> beanClass) {
        return getApplicationContext().getBean(beanClass);
    }

    public static Object getBean(String beanName) {
        return getApplicationContext().getBean(beanName);
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
